import matplotlib.pyplot as plt
import requests
from io import BytesIO


class MapDownloader:
    def __init__(self):
        self.url = "https://waf-api-takumi.mihoyo.com/common/map_user/ys_obc/v2/map/point_group?map_id=2&app_sn=ys_obc&lang=zh-cn"
        self.maps = {}
        self.maps_urls = {}
        self.get_maps_url()  # 加载maps maps_url

    def get_maps_url(self):
        response = requests.get(self.url)
        self.maps = {}
        for map_data in response.json()["data"]["list"]:
            self.maps[map_data["id"]] = map_data["floors"]
            for map in self.maps[map_data["id"]]:
                self.maps_urls[map["id"]] = map["overlay"]
                print(self.maps_urls[map["id"]])
                # 使用 update 方法合并字典
                self.maps_urls[map["id"]].update({"floor_name": map["floor_name"]})
                print(map["id"], map["floor_name"], map["overlay"]["url"])

    def get_map(self, map_id):
        try:
            map_photo = requests.get(self.maps_urls[map_id]["url"])
            return map_photo.content, {
                "floor_name": self.maps_urls[map_id]["floor_name"],
                "l_x": self.maps_urls[map_id]["l_x"],
                "l_y": self.maps_urls[map_id]["l_y"],
                "r_x": self.maps_urls[map_id]["r_x"],
                "r_y": self.maps_urls[map_id]["r_y"],
            }
        except:
            print("Error", map_id)
            return None

    def show_map(self):
        for i in self.maps.keys():
            if i == 0:
                continue
            # 下载地图覆盖层图片
            try:
                map = self.get_map(i)
                if map is None:
                    continue
                img = plt.imread(BytesIO(map[0]))
            except requests.RequestException as e:
                print(f"图片下载失败: {e}")
            else:
                # 设置图片的显示范围
                extent = (map[1]["l_x"], map[1]["r_x"], map[1]["l_y"], map[1]["r_y"])

                # 绘制地图
                plt.imshow(img, extent=extent, alpha=0.5)  # 可以设置透明度，避免完全覆盖

        # 设置一个通用标题
        plt.title("All Maps")
        # 显示所有地图
        plt.show()


if __name__ == "__main__":
    m = MapDownloader()
    m.show_map()
